package com.alibaba.citrus.cr.unified.inventory.facade.service;

import com.alibaba.citrus.cr.unified.inventory.repository.AllocateApplyOrderReadRepository;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIdsAllRequest;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIdsAllResponse;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdResponse;
import com.epoch.app.bcorder.model.dto.QueryGoodsListRequest;
import com.epoch.app.bcorder.model.dto.QueryGoodsListResponse;
import com.epoch.app.bcorder.model.dto.ScItemSDO;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.PlatformEnhanceService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crplatformenhance.scitemmultiple.model.ScItemMultiple;
import com.epoch.app.crplatformenhance.scitemmultipleread.dto.QueryRequest;
import com.epoch.app.crplatformenhance.scitemmultipleread.service.ScItemMultipleReadService;
import com.epoch.app.crpricecenter.api.pricequery.service.PriceQueryService;
import com.epoch.app.crpricecenter.dto.request.DimensionPropertyInfoRequest;
import com.epoch.app.crpricecenter.dto.request.HumanInfoRequest;
import com.epoch.app.crpricecenter.dto.request.MaterialInfoRequest;
import com.epoch.app.crpricecenter.dto.request.PlaceInfoRequest;
import com.epoch.app.crpricecenter.dto.request.PriceQueryRequest;
import com.epoch.app.crpricecenter.dto.response.ItemPriceResponse;
import com.epoch.app.crpricecenter.dto.response.PriceQueryResponse;
import com.epoch.app.crunifiedinventory.allocateapplyordergoods.service.AllocateApplyOrderGoodsService;
import com.epoch.app.crunifiedinventory.api.allocateorderread.service.AllocateOrderReadService;
import com.epoch.app.crunifiedinventory.dto.request.AllocateOrderRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateApplyOrderResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateApplyOrderQueryGoodsListDateilResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateApplyOrderQueryGoodsListResponse;
import com.epoch.app.crunifiedinventory.model.dto.ApplyOrderQueryGoodsListRequest;
import com.epoch.app.crunifiedinventory.sdo.AllocateOrderWithOrderDetailsSDO;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.stream.Collectors;


/**
 * 货品服务类
 * wwy
 */
@Service
@Primary
public class AllocateApplyOrderGoodsServiceImpl implements AllocateApplyOrderGoodsService {

    com.alibaba.cz.base.tool.log.Log log = com.alibaba.cz.base.tool.log.Log.getLogger(AllocateApplyOrderGoodsServiceImpl.class);
    /**
     * 价格类型 ZMN1 到岸价
     */
    private static final String ZMN1 = "ZMN1";
    /**
     * 空字符串
     */
    private static final String NULL_STRING = "";
    /**
     * 11
     */
    private static final String ELEVEN_STRING = "11";

    private static final String ORG_SALES_ORGANIZATION_CODE = "6000";

    /**
     * 分销渠道
     */
    private static final String CHANNELCODE = "20";

    private static final String SAP_FACTORY_CODE = "sapFactoryCode";

    private static final Integer MAX_PAGE_SIZE = 1000;


    @Autowired
    private PlatformEnhanceService platformEnhanceService;

    @Autowired
    private UnifiedInventoryService unifiedInventoryService;

    @Resource
    private AllocateApplyOrderReadRepository allocateApplyOrderReadRepository;

    @Resource
    private PriceQueryService priceQueryService;
    @Resource
    private AllocateOrderReadService allocateOrderReadService;
    @Resource
    private com.alibaba.citrus.cr.unified.inventory.repository.AllocateOrderReadRepository AllocateOrderReadRepository;

    @Autowired
    private BaseDataService baseDataService;
//    @Resource
//    private PriceWriteService priceWriteService;

    @Resource(name = "allocateApplyTaskExecutor")
    private ThreadPoolTaskExecutor allocateApplyTaskExecutor;

    @Resource
    private ScItemMultipleReadService scItemMultipleReadService;
    @Resource
    private CrUnifiedInventoryService crUnifiedInventoryService;


    public Result<List<AllocateApplyOrderQueryGoodsListResponse>> queryGoodsListNew(ApplyOrderQueryGoodsListRequest applyOrderQueryGoodsListRequest) {
        QueryGoodsListRequest queryGoodsListRequest = new QueryGoodsListRequest();
        if (CollectionUtils.isNotEmpty(applyOrderQueryGoodsListRequest.getCodes())){
            queryGoodsListRequest.setOutIdList(applyOrderQueryGoodsListRequest.getCodes().stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()));
        }
//        queryGoodsListRequest.setOutIdList(applyOrderQueryGoodsListRequest.getCodes());
        queryGoodsListRequest.setTitle(applyOrderQueryGoodsListRequest.getName());
        queryGoodsListRequest.setRecentlyUsedItemIdList(new ArrayList());
        //查询货品
        log.info("queryGoodsList applyOrderQueryGoodsListRequest {}", JSONObject.toJSONString(applyOrderQueryGoodsListRequest));
        Result<List<QueryGoodsListResponse>> queryGoodsListResponse = platformEnhanceService.queryGoodsList(queryGoodsListRequest);
        List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList = new ArrayList<>();
        if (Objects.nonNull(queryGoodsListResponse)) {
            List result = queryGoodsListResponse.getResult();
            if (CollectionUtils.isNotEmpty(result)) {
                scItemGoodsList = JSONObject.parseArray(JSONObject.toJSONString(result), AllocateApplyOrderQueryGoodsListResponse.class);
                //设置货品倍数
                setUpScItemMultiple(scItemGoodsList);
            }
        }



        //获取物料价格
        if (Objects.nonNull(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode())) {
            //获取到当前登录人的总部销售组织编码
            Result<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> saleOrganizationCode = crUnifiedInventoryService.getSaleOrganizationCode();
            String goodsGroup = NULL_STRING;
            String applyOrgId = "";
            String factoryCode = "";
            String shipWarehouseId = "";
            String applyOrgCode ="";
            if (Objects.nonNull(applyOrderQueryGoodsListRequest.getType()) && applyOrderQueryGoodsListRequest.getType() == 3) {
                //查询调拨单
                AllocateOrderRequest request = new AllocateOrderRequest();
                request.setAllocateOrderCode(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode());
                AllocateOrderWithOrderDetailsSDO allocateOrderWithOrderDetailsSDO = AllocateOrderReadRepository.get(request);
                if (Objects.nonNull(allocateOrderWithOrderDetailsSDO) && Objects.nonNull(allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO())) {
                    goodsGroup = allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO().getProductGroup();
                    applyOrgId = allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO().getApplyOrgId();
                    shipWarehouseId = allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO().getShipWarehouseId();
                }

            } else {
                //查询预报单信息
                AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode());
                if (Objects.nonNull(allocateApplyOrderResponse) && Objects.nonNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO()) && Objects.nonNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getGoodsGroup())) {
                    goodsGroup = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getGoodsGroup().toString();
                    applyOrgId = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getApplyOrg().toString();
                    shipWarehouseId = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getShipWarehouseId();
                }
            }
        //通过发货仓id查找逻辑仓库中所需要的数据
            if (StringUtil.isNotEmpty(shipWarehouseId)) {
                QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
                queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(shipWarehouseId));
                QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
                if (Objects.nonNull(queryCargoZoneByIdResponse) && org.apache.commons.collections.CollectionUtils.isNotEmpty(queryCargoZoneByIdResponse.getResult())) {
                    Map<String, String> result = (Map<String, String>) queryCargoZoneByIdResponse.getResult().get(0);
                    //工厂code
                    factoryCode = result.get(SAP_FACTORY_CODE);
                }
            }
            BaselineGetOrganizationByIdsAllRequest baselineGetOrganizationByIdsAllRequest = new BaselineGetOrganizationByIdsAllRequest();
            List<String> ids = new ArrayList<>();
            ids.add(applyOrgId);
            baselineGetOrganizationByIdsAllRequest.setIds(ids);
            BaselineGetOrganizationByIdsAllResponse baselineGetOrganizationByIdsAllResponse = baseDataService.baselineGetOrganizationByIdsAll(baselineGetOrganizationByIdsAllRequest);
            if (Objects.nonNull(baselineGetOrganizationByIdsAllResponse)){
                List<OrganizationSDO> organizationSDOS = baselineGetOrganizationByIdsAllResponse.getResult();
                if (CollectionUtils.isNotEmpty(organizationSDOS)){
                    applyOrgCode = organizationSDOS.get(0).getOutCode();
                }
            }
            /**
             * 查询价格维度
             * 物料：货品的outer_id
             * 货品组：固定11；
             * 工厂：发货仓的工厂CODE；
             * 客户：提报组织的编码；
             * 组织：固定6000，
             * 分销渠道：固定20；
             *
             * 当前接口的批量查询的最大货品数量是 50 个，建议使用同一个枚举值并行限制。
             * 建议当前使用这个值：
             * com.alibaba.citrus.cr.price.common.PriceAcmConfig#MAX_ITEM_COUNT_PER_QUERY
             */
            List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = new ArrayList<>();
//            List<String> ids = new ArrayList<>();
            for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                    DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
                    //价格类型 ZMN1 到岸价
                    dimensionPropertyInfoRequest.setPriceTypeId(ZMN1);
                    //价格的使用时间
                    dimensionPropertyInfoRequest.setPriceUseDate(new Date());
                    /**
                     * 货的信息
                     *  产品组编码
                     *  货品编码
                     */
//                    ids.add(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                    MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
                    materialInfoRequest.setMaterialCode(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                    if (StringUtil.isNotEmpty(goodsGroup)) {
                        materialInfoRequest.setScItemGroupCode(goodsGroup);
                    } else {
                        materialInfoRequest.setScItemGroupCode(ELEVEN_STRING);
                    }
                    dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
                    /**
                     * 人的信息:
                     *  客户 =提报组织的编码
                     *  送达方编码
                     *  售达方编码， = 提报组织的编码
                     *  客户组编码，
                     *  价目清单编码
                     */
                    HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
                    if (StringUtil.isNotEmpty(applyOrgCode)){
                        humanInfoRequest.setCustomerCode(applyOrgCode);
                        humanInfoRequest.setCustomerSaleAddressCode(applyOrgCode);
                    }
                    dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
                    /**
                     * 场的信息
                     *   销售组织编码
                     *   分销渠道编码
                     *   销售单位编码
                     *   销售地区编码
                     *   工厂编码
                     *   销售部
                     *   销售组
                     *   存储位置
                     *   部门
                     *   定价区域
                     */
                    PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
                    //总部销售组织编码
                    placeInfoRequest.setOrgSalesOrganizationCode(Optional.ofNullable(saleOrganizationCode).map(Result::getResult).map(com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getCode).orElse(ORG_SALES_ORGANIZATION_CODE));
                    placeInfoRequest.setChannelCode(CHANNELCODE);
                    if (StringUtil.isNotEmpty(factoryCode)) {
                        placeInfoRequest.setFactoryCode(factoryCode);
                    }
                    dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);
                    dimensionPropertyInfoRequestList.add(dimensionPropertyInfoRequest);
                }
            }
            log.info("AllocateApplyOrderGoodsServiceImpl_queryGoodsListNew,request:{}", JSONObject.toJSONString(dimensionPropertyInfoRequestList));
            List<ItemPriceResponse> resultList = new ArrayList<>();
            int size = dimensionPropertyInfoRequestList.size();
            List<Future<PriceQueryResponse>> futures = new ArrayList<>();
            for (int i=0;i<size;i++){
                int end = i + 50;
                int start = i;
                try{
                    CompletableFuture<PriceQueryResponse> future = CompletableFuture.supplyAsync(()->{
                        PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
                        priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList.subList(start, end > size ? size : end));
                        Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPrice(priceQueryRequest);
                        if(Objects.nonNull(priceQueryResponseResult) && Objects.nonNull(priceQueryResponseResult.getResult())) {
                            PriceQueryResponse priceQueryResponse = priceQueryResponseResult.getResult();
                            return priceQueryResponse;
                        }
                        return null;
                    },allocateApplyTaskExecutor);
                    futures.add(future);

                }catch (Exception e){
                    e.printStackTrace();
                }
                i = end - 1;
            }

            if (CollectionUtils.isNotEmpty(futures)){
                try {
                    for (Future<PriceQueryResponse> future : futures) {
                        PriceQueryResponse priceQueryResponse = future.get();
                        if ( priceQueryResponse != null){
                            List<ItemPriceResponse> priceResponseList = priceQueryResponse.getItemPriceResponseList();
                            if (CollectionUtils.isNotEmpty(priceResponseList)){
                                resultList.addAll(priceResponseList);
                            }
                        }
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            log.info("AllocateApplyOrderGoodsServiceImpl_queryGoodsListNew,result:{}", JSONObject.toJSONString(resultList));
            if (Objects.nonNull(resultList)) {
                //到岸价map
                Map<String, BigDecimal> CIFPriceMap = new HashMap<>();
                for (ItemPriceResponse itemPriceResponse : resultList) {
                    //根据货品id 获取价格
                    //货品id
                    String itemId = itemPriceResponse.getItemId();
                    //价格 分为单位
                    Long moneyAmout = itemPriceResponse.getMoneyAmout();
                    if (Objects.nonNull(moneyAmout)) {
                        if (moneyAmout > 0) {
                            BigDecimal doubleValue = new BigDecimal(moneyAmout.doubleValue() / 100).setScale(2, RoundingMode.HALF_UP);
                            CIFPriceMap.put(itemId, doubleValue);
                        }
                    }
                }
                for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                    for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                        BigDecimal cIFPrice = CIFPriceMap.get(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                        if (Objects.nonNull(cIFPrice)) {
                            allocateApplyOrderQueryGoodsListDateilResponse.setCIFPrice(cIFPrice);
                            allocateApplyOrderQueryGoodsListDateilResponse.setPrice(cIFPrice);
                        }
                    }
                }
            }
        }
        return Result.success(scItemGoodsList);
    }

    @Override
    public Result<List<AllocateApplyOrderQueryGoodsListResponse>> queryGoodsList(ApplyOrderQueryGoodsListRequest applyOrderQueryGoodsListRequest) {
        //用多线程的方式 先试试看
        if (true){
            return queryGoodsListNew(applyOrderQueryGoodsListRequest);
        }
        QueryGoodsListRequest queryGoodsListRequest = new QueryGoodsListRequest();
        queryGoodsListRequest.setOutIdList(applyOrderQueryGoodsListRequest.getCodes());
        queryGoodsListRequest.setTitle(applyOrderQueryGoodsListRequest.getName());
        queryGoodsListRequest.setRecentlyUsedItemIdList(new ArrayList());
        //查询货品
        log.info("queryGoodsList applyOrderQueryGoodsListRequest {}", JSONObject.toJSONString(applyOrderQueryGoodsListRequest));
        Result<List<QueryGoodsListResponse>> queryGoodsListResponse = platformEnhanceService.queryGoodsList(queryGoodsListRequest);
        List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList = new ArrayList<>();
        if (Objects.nonNull(queryGoodsListResponse)) {
            List result = queryGoodsListResponse.getResult();
            if (CollectionUtils.isNotEmpty(result)) {
                scItemGoodsList = JSONObject.parseArray(JSONObject.toJSONString(result), AllocateApplyOrderQueryGoodsListResponse.class);
            }
        }

        //获取物料价格
        if (Objects.nonNull(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode())) {
            String goodsGroup = NULL_STRING;
            if (Objects.nonNull(applyOrderQueryGoodsListRequest.getType()) && applyOrderQueryGoodsListRequest.getType() == 3) {
                //查询调拨单
                AllocateOrderRequest request = new AllocateOrderRequest();
                request.setAllocateOrderCode(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode());
                AllocateOrderWithOrderDetailsSDO allocateOrderWithOrderDetailsSDO = AllocateOrderReadRepository.get(request);
                if (Objects.nonNull(allocateOrderWithOrderDetailsSDO) && Objects.nonNull(allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO())) {
                    goodsGroup = allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO().getProductGroup();
                }

            } else {
                //查询预报单信息
                AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode());
                if (Objects.nonNull(allocateApplyOrderResponse) && Objects.nonNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO()) && Objects.nonNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getGoodsGroup())) {
                    goodsGroup = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getGoodsGroup().toString();
                }
            }
            /**
             * 当前接口的批量查询的最大货品数量是 50 个，建议使用同一个枚举值并行限制。
             * 建议当前使用这个值：
             * com.alibaba.citrus.cr.price.common.PriceAcmConfig#MAX_ITEM_COUNT_PER_QUERY
             */
            List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = new ArrayList<>();
//            List<String> ids = new ArrayList<>();
            for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                    DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
                    //价格类型 ZMN1 到岸价
                    dimensionPropertyInfoRequest.setPriceTypeId(ZMN1);
                    //价格的使用时间
                    dimensionPropertyInfoRequest.setPriceUseDate(new Date());
                    /**
                     * 货的信息
                     *  产品组编码
                     *  货品编码
                     */
//                    ids.add(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                    MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
                    materialInfoRequest.setMaterialCode(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                    if (StringUtil.isNotEmpty(goodsGroup)) {
                        materialInfoRequest.setScItemGroupCode(goodsGroup);
                    } else {
                        materialInfoRequest.setScItemGroupCode(ELEVEN_STRING);
                    }
                    dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
                    /**
                     * 人的信息:
                     *  客户
                     *  送达方编码
                     *  售达方编码，
                     *  客户组编码，
                     *  价目清单编码
                     */
                    HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
                    dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
                    /**
                     * 场的信息
                     *   销售组织编码
                     *   分销渠道编码
                     *   销售单位编码
                     *   销售地区编码
                     *   工厂编码
                     *   销售部
                     *   销售组
                     *   存储位置
                     *   部门
                     *   定价区域
                     */
                    PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
                    placeInfoRequest.setOrgSalesOrganizationCode(ORG_SALES_ORGANIZATION_CODE);
                    dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);
                    dimensionPropertyInfoRequestList.add(dimensionPropertyInfoRequest);
                }
            }
            List<ItemPriceResponse> resultList = new ArrayList<>();
            int size = dimensionPropertyInfoRequestList.size();
//            SyncPriceDimensionConfigDataRequest syncPriceDimensionConfigDataRequest = new SyncPriceDimensionConfigDataRequest();
//            for (String id:ids){
//                syncPriceDimensionConfigDataRequest.setPriceEndDate(new Date(new Date().getTime()+1000000000L));
//                syncPriceDimensionConfigDataRequest.setDimensionId("w17");
//                syncPriceDimensionConfigDataRequest.setTenantId("tna");
//                syncPriceDimensionConfigDataRequest.setPriceTypeId("ZMN1");
//                syncPriceDimensionConfigDataRequest.setPriceRecordId("19323");
//                syncPriceDimensionConfigDataRequest.setTableName("A904");
//                syncPriceDimensionConfigDataRequest.setPriceStartDate(new Date());
//
//                ArrayList<DimensionProperty> list = Lists.newArrayList();
//                DimensionProperty dimensionProperty1 = new DimensionProperty();
//                dimensionProperty1.setDimensionName("org_sales_organization_code");
//                dimensionProperty1.setDimensionValue("6000");
//                list.add(dimensionProperty1);
//                DimensionProperty dimensionProperty2 = new DimensionProperty();
//                dimensionProperty2.setDimensionName("sc_item_group_code");
//                dimensionProperty2.setDimensionValue("11");
//                list.add(dimensionProperty2);
//                DimensionProperty dimensionProperty3 = new DimensionProperty();
//                dimensionProperty3.setDimensionName("material_code");
//                dimensionProperty3.setDimensionValue(id);
//                list.add(dimensionProperty3);
//                syncPriceDimensionConfigDataRequest.setDimensionPropertyList(list);
//                priceWriteService.syncPricePropertyConfigData(syncPriceDimensionConfigDataRequest);
//            }
            for (int i = 0; i < size; i++) {
                int end = i + 50;
                PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
                priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList.subList(i, end > size ? size : end));
                Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPrice(priceQueryRequest);
                if (Objects.nonNull(priceQueryResponseResult) && Objects.nonNull(priceQueryResponseResult.getResult())) {
                    PriceQueryResponse priceQueryResponse = priceQueryResponseResult.getResult();
                    List<ItemPriceResponse> list = priceQueryResponse.getItemPriceResponseList();
                    resultList.addAll(list);
                }
                i = end - 1;
            }


            if (Objects.nonNull(resultList)) {
                //到岸价map
                Map<String, BigDecimal> CIFPriceMap = new HashMap<>();
                for (ItemPriceResponse itemPriceResponse : resultList) {
                    //根据货品id 获取价格
                    //货品id
                    String itemId = itemPriceResponse.getItemId();
                    //价格 分为单位
                    Long moneyAmout = itemPriceResponse.getMoneyAmout();
                    if (Objects.nonNull(moneyAmout)) {
                        if (moneyAmout > 0) {
                            BigDecimal doubleValue = new BigDecimal(moneyAmout.doubleValue() / 100).setScale(2, RoundingMode.HALF_UP);
                            CIFPriceMap.put(itemId, doubleValue);
                        }
                    }
                }
                for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                    for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                        BigDecimal cIFPrice = CIFPriceMap.get(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                        if (Objects.nonNull(cIFPrice)) {
                            allocateApplyOrderQueryGoodsListDateilResponse.setCIFPrice(cIFPrice);
                            allocateApplyOrderQueryGoodsListDateilResponse.setPrice(cIFPrice);
                        }
                    }
                }
            }
        }
        return Result.success(scItemGoodsList);
    }

    @Override
    public Result<List<AllocateApplyOrderQueryGoodsListDateilResponse>> queryNotClassifiedGoodsList(ApplyOrderQueryGoodsListRequest applyOrderQueryGoodsListRequest) {
        //查询货品
        SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
        searchScItemRequest.setPageSize(3000);
        JSONObject searchReqDTO = new JSONObject();
        searchReqDTO.put("outerIdList", applyOrderQueryGoodsListRequest.getCodes());
        searchReqDTO.put("businessType","11");//业态常温
        searchReqDTO.put("type",0);//非组合货品
        searchScItemRequest.setSearchReqDTO(searchReqDTO);
        log.info("queryGoodsList applyOrderQueryGoodsListRequest {}", JSONObject.toJSONString(applyOrderQueryGoodsListRequest));
        Result<List<ScItemSDO>> queryGoodsListResponse = baseDataService.searchScItem(searchScItemRequest);

        List<AllocateApplyOrderQueryGoodsListDateilResponse> allocateApplyOrderQueryGoodsListDateilResponses = new ArrayList<>();
        if (Objects.nonNull(queryGoodsListResponse)&&CollectionUtils.isNotEmpty(queryGoodsListResponse.getResult())) {
            //数据转换
            List<ScItemSDO> scItemSDOS = queryGoodsListResponse.getResult();
            for (ScItemSDO scItemSDO:scItemSDOS){
                AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse = new AllocateApplyOrderQueryGoodsListDateilResponse();
                allocateApplyOrderQueryGoodsListDateilResponse.setGoodsCode(scItemSDO.getOuterId());
                allocateApplyOrderQueryGoodsListDateilResponse.setGoodsName(scItemSDO.getTitle());
                Map<String,String> features = scItemSDO.getFeatures();
                allocateApplyOrderQueryGoodsListDateilResponse.setBaseUnitCode(features.get("unitName"));
                List<String> list = new ArrayList<>();
                list.add(scItemSDO.getUnit());
                allocateApplyOrderQueryGoodsListDateilResponse.setUnitName(list);
//                allocateApplyOrderQueryGoodsListDateilResponse.setDailyInventory();
//                allocateApplyOrderQueryGoodsListDateilResponse.setInvertoryUnit();
                allocateApplyOrderQueryGoodsListDateilResponses.add(allocateApplyOrderQueryGoodsListDateilResponse);
            }
        }

        //获取物料价格
        if (Objects.nonNull(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode())) {
            String goodsGroup = NULL_STRING;
            if (Objects.nonNull(applyOrderQueryGoodsListRequest.getType()) && applyOrderQueryGoodsListRequest.getType() == 3) {
                //查询调拨单
                AllocateOrderRequest request = new AllocateOrderRequest();
                request.setAllocateOrderCode(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode());
                AllocateOrderWithOrderDetailsSDO allocateOrderWithOrderDetailsSDO = AllocateOrderReadRepository.get(request);
                if (Objects.nonNull(allocateOrderWithOrderDetailsSDO) && Objects.nonNull(allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO())) {
                    goodsGroup = allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO().getProductGroup();
                }

            } else {
                //查询预报单信息
                AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode());
                if (Objects.nonNull(allocateApplyOrderResponse) && Objects.nonNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO()) && Objects.nonNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getGoodsGroup())) {
                    goodsGroup = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getGoodsGroup().toString();
                }
            }
            /**
             * 当前接口的批量查询的最大货品数量是 50 个，建议使用同一个枚举值并行限制。
             * 建议当前使用这个值：
             * com.alibaba.citrus.cr.price.common.PriceAcmConfig#MAX_ITEM_COUNT_PER_QUERY
             */
            List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = new ArrayList<>();
//            List<String> ids = new ArrayList<>();
            for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListDateilResponses) {
                DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
                //价格类型 ZMN1 到岸价
                dimensionPropertyInfoRequest.setPriceTypeId(ZMN1);
                //价格的使用时间
                dimensionPropertyInfoRequest.setPriceUseDate(new Date());
                /**
                 * 货的信息
                 *  产品组编码
                 *  货品编码
                 */
//                    ids.add(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
                materialInfoRequest.setMaterialCode(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                if (StringUtil.isNotEmpty(goodsGroup)) {
                    materialInfoRequest.setScItemGroupCode(goodsGroup);
                } else {
                    materialInfoRequest.setScItemGroupCode(ELEVEN_STRING);
                }
                dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
                /**
                 * 人的信息:
                 *  客户
                 *  送达方编码
                 *  售达方编码，
                 *  客户组编码，
                 *  价目清单编码
                 */
                HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
                dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
                /**
                 * 场的信息
                 *   销售组织编码
                 *   分销渠道编码
                 *   销售单位编码
                 *   销售地区编码
                 *   工厂编码
                 *   销售部
                 *   销售组
                 *   存储位置
                 *   部门
                 *   定价区域
                 */
                PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
                placeInfoRequest.setOrgSalesOrganizationCode(ORG_SALES_ORGANIZATION_CODE);
                dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);
                dimensionPropertyInfoRequestList.add(dimensionPropertyInfoRequest);
            }
            List<ItemPriceResponse> resultList = new ArrayList<>();
            int size = dimensionPropertyInfoRequestList.size();
            for (int i = 0; i < size; i++) {
                int end = i + 50;
                PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
                priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList.subList(i, end > size ? size : end));
                Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPrice(priceQueryRequest);
                if (Objects.nonNull(priceQueryResponseResult) && Objects.nonNull(priceQueryResponseResult.getResult())) {
                    PriceQueryResponse priceQueryResponse = priceQueryResponseResult.getResult();
                    List<ItemPriceResponse> list = priceQueryResponse.getItemPriceResponseList();
                    resultList.addAll(list);
                }
                i = end - 1;
            }


            if (Objects.nonNull(resultList)) {
                //到岸价map
                Map<String, BigDecimal> CIFPriceMap = new HashMap<>();
                for (ItemPriceResponse itemPriceResponse : resultList) {
                    //根据货品id 获取价格
                    //货品id
                    String itemId = itemPriceResponse.getItemId();
                    //价格 分为单位
                    Long moneyAmout = itemPriceResponse.getMoneyAmout();
                    if (Objects.nonNull(moneyAmout)) {
                        if (moneyAmout > 0) {
                            BigDecimal doubleValue = new BigDecimal(moneyAmout.doubleValue() / 100).setScale(2, RoundingMode.HALF_UP);
                            CIFPriceMap.put(itemId, doubleValue);
                        }
                    }
                }

                for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListDateilResponses) {
                    BigDecimal cIFPrice = CIFPriceMap.get(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                    if (Objects.nonNull(cIFPrice)) {
                        allocateApplyOrderQueryGoodsListDateilResponse.setCIFPrice(cIFPrice);
                        allocateApplyOrderQueryGoodsListDateilResponse.setPrice(cIFPrice);
                    }
                }
            }
        }
        return Result.success(allocateApplyOrderQueryGoodsListDateilResponses);
    }

    @Override
    public Result<List<AllocateApplyOrderQueryGoodsListResponse>> queryGoodsListQuickly(ApplyOrderQueryGoodsListRequest applyOrderQueryGoodsListRequest) {
        //快速添加
        return queryGoodsListNewQuickly(applyOrderQueryGoodsListRequest);
    }

    public Result<List<AllocateApplyOrderQueryGoodsListResponse>> queryGoodsListNewQuickly(ApplyOrderQueryGoodsListRequest applyOrderQueryGoodsListRequest) {
        QueryGoodsListRequest queryGoodsListRequest = new QueryGoodsListRequest();
        if (CollectionUtils.isNotEmpty(applyOrderQueryGoodsListRequest.getCodes())){
            queryGoodsListRequest.setOutIdList(applyOrderQueryGoodsListRequest.getCodes().stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()));
        }
//        queryGoodsListRequest.setOutIdList(applyOrderQueryGoodsListRequest.getCodes());
        queryGoodsListRequest.setTitle(applyOrderQueryGoodsListRequest.getName());
        queryGoodsListRequest.setRecentlyUsedItemIdList(new ArrayList());
        //查询货品
        log.info("queryGoodsList applyOrderQueryGoodsListRequest {}", JSONObject.toJSONString(applyOrderQueryGoodsListRequest));
        Result<List<QueryGoodsListResponse>> queryGoodsListResponse = platformEnhanceService.queryGoodsList(queryGoodsListRequest);
        List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList = new ArrayList<>();
        //快速添加
        List<AllocateApplyOrderQueryGoodsListResponse> quicklyGoodsList = Lists.newArrayList();
        if (Objects.nonNull(queryGoodsListResponse)) {
            List result = queryGoodsListResponse.getResult();
            if (CollectionUtils.isNotEmpty(result)) {
                scItemGoodsList = JSONObject.parseArray(JSONObject.toJSONString(result), AllocateApplyOrderQueryGoodsListResponse.class);
            }
        }


        //获取物料价格
        if (Objects.nonNull(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode())) {
            Result<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> saleOrganizationCode = crUnifiedInventoryService.getSaleOrganizationCode();
            String goodsGroup = NULL_STRING;
            String applyOrgId = "";
            String factoryCode = "";
            String shipWarehouseId = "";
            String applyOrgCode ="";
            if (Objects.nonNull(applyOrderQueryGoodsListRequest.getType()) && applyOrderQueryGoodsListRequest.getType() == 3) {
                //查询调拨单
                AllocateOrderRequest request = new AllocateOrderRequest();
                request.setAllocateOrderCode(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode());
                AllocateOrderWithOrderDetailsSDO allocateOrderWithOrderDetailsSDO = AllocateOrderReadRepository.get(request);
                if (Objects.nonNull(allocateOrderWithOrderDetailsSDO) && Objects.nonNull(allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO())) {
                    goodsGroup = allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO().getProductGroup();
                    applyOrgId = allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO().getApplyOrgId();
                    shipWarehouseId = allocateOrderWithOrderDetailsSDO.getAllocateOrderSDO().getShipWarehouseId();
                }

            } else {
                //查询预报单信息
                AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(applyOrderQueryGoodsListRequest.getApplyOrderQueryCode());
                if (Objects.nonNull(allocateApplyOrderResponse) && Objects.nonNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO()) && Objects.nonNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getGoodsGroup())) {
                    goodsGroup = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getGoodsGroup().toString();
                    applyOrgId = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getApplyOrg().toString();
                    shipWarehouseId = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getShipWarehouseId();
                }
            }
            //通过发货仓id查找逻辑仓库中所需要的数据
            if (StringUtil.isNotEmpty(shipWarehouseId)) {
                QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
                queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(shipWarehouseId));
                QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
                if (Objects.nonNull(queryCargoZoneByIdResponse) && org.apache.commons.collections.CollectionUtils.isNotEmpty(queryCargoZoneByIdResponse.getResult())) {
                    Map<String, String> result = (Map<String, String>) queryCargoZoneByIdResponse.getResult().get(0);
                    //工厂code
                    factoryCode = result.get(SAP_FACTORY_CODE);
                }
            }
            BaselineGetOrganizationByIdsAllRequest baselineGetOrganizationByIdsAllRequest = new BaselineGetOrganizationByIdsAllRequest();
            List<String> ids = new ArrayList<>();
            ids.add(applyOrgId);
            baselineGetOrganizationByIdsAllRequest.setIds(ids);
            BaselineGetOrganizationByIdsAllResponse baselineGetOrganizationByIdsAllResponse = baseDataService.baselineGetOrganizationByIdsAll(baselineGetOrganizationByIdsAllRequest);
            if (Objects.nonNull(baselineGetOrganizationByIdsAllResponse)){
                List<OrganizationSDO> organizationSDOS = baselineGetOrganizationByIdsAllResponse.getResult();
                if (CollectionUtils.isNotEmpty(organizationSDOS)){
                    applyOrgCode = organizationSDOS.get(0).getOutCode();
                }
            }
            /**
             * 查询价格维度
             * 物料：货品的outer_id
             * 货品组：固定11；
             * 工厂：发货仓的工厂CODE；
             * 客户：提报组织的编码；
             * 组织：固定6000，
             * 分销渠道：固定20；
             *
             * 当前接口的批量查询的最大货品数量是 50 个，建议使用同一个枚举值并行限制。
             * 建议当前使用这个值：
             * com.alibaba.citrus.cr.price.common.PriceAcmConfig#MAX_ITEM_COUNT_PER_QUERY
             */
            List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = new ArrayList<>();
//            List<String> ids = new ArrayList<>();
            for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                    DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
                    //价格类型 ZMN1 到岸价
                    dimensionPropertyInfoRequest.setPriceTypeId(ZMN1);
                    //价格的使用时间
                    dimensionPropertyInfoRequest.setPriceUseDate(new Date());
                    /**
                     * 货的信息
                     *  产品组编码
                     *  货品编码
                     */
//                    ids.add(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                    MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
                    materialInfoRequest.setMaterialCode(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                    if (StringUtil.isNotEmpty(goodsGroup)) {
                        materialInfoRequest.setScItemGroupCode(goodsGroup);
                    } else {
                        materialInfoRequest.setScItemGroupCode(ELEVEN_STRING);
                    }
                    dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
                    /**
                     * 人的信息:
                     *  客户 =提报组织的编码
                     *  送达方编码
                     *  售达方编码， = 提报组织的编码
                     *  客户组编码，
                     *  价目清单编码
                     */
                    HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
                    if (StringUtil.isNotEmpty(applyOrgCode)){
                        humanInfoRequest.setCustomerCode(applyOrgCode);
                        humanInfoRequest.setCustomerSaleAddressCode(applyOrgCode);
                    }
                    dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
                    /**
                     * 场的信息
                     *   销售组织编码
                     *   分销渠道编码
                     *   销售单位编码
                     *   销售地区编码
                     *   工厂编码
                     *   销售部
                     *   销售组
                     *   存储位置
                     *   部门
                     *   定价区域
                     */
                    PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
                    //获取当前登录人的总部销售组织编码
                    placeInfoRequest.setOrgSalesOrganizationCode(Optional.ofNullable(saleOrganizationCode).map(Result::getResult).map(com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getCode).orElse(ORG_SALES_ORGANIZATION_CODE));
                    placeInfoRequest.setChannelCode(CHANNELCODE);
                    if (StringUtil.isNotEmpty(factoryCode)) {
                        placeInfoRequest.setFactoryCode(factoryCode);
                    }
                    dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);
                    dimensionPropertyInfoRequestList.add(dimensionPropertyInfoRequest);
                }
            }
            log.info("AllocateApplyOrderGoodsServiceImpl_queryGoodsListNew,request:{}", JSONObject.toJSONString(dimensionPropertyInfoRequestList));
            List<ItemPriceResponse> resultList = new ArrayList<>();
            int size = dimensionPropertyInfoRequestList.size();
            List<Future<PriceQueryResponse>> futures = new ArrayList<>();
            for (int i=0;i<size;i++){
                int end = i + 50;
                int start = i;
                try{
                    CompletableFuture<PriceQueryResponse> future = CompletableFuture.supplyAsync(()->{
                        PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
                        priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList.subList(start, end > size ? size : end));
                        Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPrice(priceQueryRequest);
                        if(Objects.nonNull(priceQueryResponseResult) && Objects.nonNull(priceQueryResponseResult.getResult())) {
                            PriceQueryResponse priceQueryResponse = priceQueryResponseResult.getResult();
                            return priceQueryResponse;
                        }
                        return null;
                    },allocateApplyTaskExecutor);
                    futures.add(future);

                }catch (Exception e){
                    e.printStackTrace();
                }
                i = end - 1;
            }

            if (CollectionUtils.isNotEmpty(futures)){
                try {
                    for (Future<PriceQueryResponse> future : futures) {
                        PriceQueryResponse priceQueryResponse = future.get();
                        if ( priceQueryResponse != null){
                            List<ItemPriceResponse> priceResponseList = priceQueryResponse.getItemPriceResponseList();
                            if (CollectionUtils.isNotEmpty(priceResponseList)){
                                resultList.addAll(priceResponseList);
                            }
                        }
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            log.info("AllocateApplyOrderGoodsServiceImpl_queryGoodsListNew,result:{}", JSONObject.toJSONString(resultList));
            if (Objects.nonNull(resultList)) {
                //到岸价map
                Map<String, BigDecimal> CIFPriceMap = new HashMap<>();
                for (ItemPriceResponse itemPriceResponse : resultList) {
                    //根据货品id 获取价格
                    //货品id
                    String itemId = itemPriceResponse.getItemId();
                    //价格 分为单位
                    Long moneyAmout = itemPriceResponse.getMoneyAmout();
                    if (Objects.nonNull(moneyAmout)) {
                        if (moneyAmout > 0) {
                            BigDecimal doubleValue = new BigDecimal(moneyAmout.doubleValue() / 100).setScale(2, RoundingMode.HALF_UP);
                            CIFPriceMap.put(itemId, doubleValue);
                        }
                    }
                }
                for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                    for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                        BigDecimal cIFPrice = CIFPriceMap.get(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                        if (Objects.nonNull(cIFPrice)) {
                            allocateApplyOrderQueryGoodsListDateilResponse.setCIFPrice(cIFPrice);
                            allocateApplyOrderQueryGoodsListDateilResponse.setPrice(cIFPrice);
                        }
                    }
                }
            }
        }
        //如果有结果
        if (CollectionUtils.isNotEmpty(scItemGoodsList)){
            List<String> codes = applyOrderQueryGoodsListRequest.getCodes();
            List<AllocateApplyOrderQueryGoodsListDateilResponse> dateilResponses = scItemGoodsList.stream().map(AllocateApplyOrderQueryGoodsListResponse::getGoodsList)
                    .flatMap(Collection::stream).collect(Collectors.toList());
            AllocateApplyOrderQueryGoodsListResponse quiclyResponse = new AllocateApplyOrderQueryGoodsListResponse();
            if (CollectionUtils.isNotEmpty(codes) && CollectionUtils.isNotEmpty(dateilResponses)){
                List<AllocateApplyOrderQueryGoodsListDateilResponse> quicklyListDateilResponses = Lists.newArrayList();
                for (String code : codes) {
                    AllocateApplyOrderQueryGoodsListDateilResponse goodsListDateilResponse = dateilResponses.stream().filter(x -> Objects.equals(code, x.getGoodsCode())).findFirst().orElse(null);
                    if (goodsListDateilResponse != null){
                        quicklyListDateilResponses.add(goodsListDateilResponse);
                    }
                }
                quiclyResponse.setGoodsList(quicklyListDateilResponses);
                quicklyGoodsList.add(quiclyResponse);
            }
        }

        return Result.success(quicklyGoodsList);
    }


    /**
     * 预报单导入时查询价格
     * @param applyOrderQueryGoodsListRequest
     * @return
     */
    @Override
    public Result<List<AllocateApplyOrderQueryGoodsListResponse>> queryGoodsListForImport(ApplyOrderQueryGoodsListRequest applyOrderQueryGoodsListRequest) {
        QueryGoodsListRequest queryGoodsListRequest = new QueryGoodsListRequest();
        if (CollectionUtils.isNotEmpty(applyOrderQueryGoodsListRequest.getCodes())){
            queryGoodsListRequest.setOutIdList(applyOrderQueryGoodsListRequest.getCodes().stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()));
        }
        queryGoodsListRequest.setOutIdList(applyOrderQueryGoodsListRequest.getCodes());
        queryGoodsListRequest.setTitle(applyOrderQueryGoodsListRequest.getName());
        queryGoodsListRequest.setRecentlyUsedItemIdList(new ArrayList());
        //查询货品
        log.info("queryGoodsList applyOrderQueryGoodsListRequest {}", JSONObject.toJSONString(applyOrderQueryGoodsListRequest));
        Result<List<QueryGoodsListResponse>> queryGoodsListResponse = platformEnhanceService.queryGoodsList(queryGoodsListRequest);
        List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList = new ArrayList<>();
        if (Objects.nonNull(queryGoodsListResponse)) {
            List result = queryGoodsListResponse.getResult();
            if (CollectionUtils.isNotEmpty(result)) {
                scItemGoodsList = JSONObject.parseArray(JSONObject.toJSONString(result), AllocateApplyOrderQueryGoodsListResponse.class);
            }
        }


        //获取物料价格

        String goodsGroup = applyOrderQueryGoodsListRequest.getGoodsGroup();
        String applyOrgId = applyOrderQueryGoodsListRequest.getApplyOrgId();
        String factoryCode = "";
        String shipWarehouseId = applyOrderQueryGoodsListRequest.getShipWarehouseId();
        String applyOrgCode ="";

        //通过发货仓id查找逻辑仓库中所需要的数据
        if (StringUtil.isNotEmpty(shipWarehouseId)) {
            QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
            queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(shipWarehouseId));
            QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
            if (Objects.nonNull(queryCargoZoneByIdResponse) && org.apache.commons.collections.CollectionUtils.isNotEmpty(queryCargoZoneByIdResponse.getResult())) {
                Map<String, String> result = (Map<String, String>) queryCargoZoneByIdResponse.getResult().get(0);
                //工厂code
                factoryCode = result.get(SAP_FACTORY_CODE);
            }
        }
        BaselineGetOrganizationByIdsAllRequest baselineGetOrganizationByIdsAllRequest = new BaselineGetOrganizationByIdsAllRequest();
        List<String> ids = new ArrayList<>();
        ids.add(applyOrgId);
        baselineGetOrganizationByIdsAllRequest.setIds(ids);
        BaselineGetOrganizationByIdsAllResponse baselineGetOrganizationByIdsAllResponse = baseDataService.baselineGetOrganizationByIdsAll(baselineGetOrganizationByIdsAllRequest);
        if (Objects.nonNull(baselineGetOrganizationByIdsAllResponse)){
            List<OrganizationSDO> organizationSDOS = baselineGetOrganizationByIdsAllResponse.getResult();
            if (CollectionUtils.isNotEmpty(organizationSDOS)){
                applyOrgCode = organizationSDOS.get(0).getOutCode();
            }
        }
        /**
         * 查询价格维度
         * 物料：货品的outer_id
         * 货品组：固定11；
         * 工厂：发货仓的工厂CODE；
         * 客户：提报组织的编码；
         * 组织：固定6000，
         * 分销渠道：固定20；
         *
         * 当前接口的批量查询的最大货品数量是 50 个，建议使用同一个枚举值并行限制。
         * 建议当前使用这个值：
         * com.alibaba.citrus.cr.price.common.PriceAcmConfig#MAX_ITEM_COUNT_PER_QUERY
         */
        List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = new ArrayList<>();
        Result<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> saleOrganizationCode = crUnifiedInventoryService.getSaleOrganizationCode();
        for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
            for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
                //价格类型 ZMN1 到岸价
                dimensionPropertyInfoRequest.setPriceTypeId(ZMN1);
                //价格的使用时间
                dimensionPropertyInfoRequest.setPriceUseDate(new Date());
                /**
                 * 货的信息
                 *  产品组编码
                 *  货品编码
                 */
//                    ids.add(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
                materialInfoRequest.setMaterialCode(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                if (StringUtil.isNotEmpty(goodsGroup)) {
                    materialInfoRequest.setScItemGroupCode(goodsGroup);
                } else {
                    materialInfoRequest.setScItemGroupCode(ELEVEN_STRING);
                }
                dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
                /**
                 * 人的信息:
                 *  客户 =提报组织的编码
                 *  送达方编码
                 *  售达方编码， = 提报组织的编码
                 *  客户组编码，
                 *  价目清单编码
                 */
                HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
                if (StringUtil.isNotEmpty(applyOrgCode)){
                    humanInfoRequest.setCustomerCode(applyOrgCode);
                    humanInfoRequest.setCustomerSaleAddressCode(applyOrgCode);
                }
                dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
                /**
                 * 场的信息
                 *   销售组织编码
                 *   分销渠道编码
                 *   销售单位编码
                 *   销售地区编码
                 *   工厂编码
                 *   销售部
                 *   销售组
                 *   存储位置
                 *   部门
                 *   定价区域
                 */
                PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
                //获取总部销售组织编码
                placeInfoRequest.setOrgSalesOrganizationCode(Optional.ofNullable(saleOrganizationCode).map(Result::getResult).map(com.epoch.app.crplatformenhance.sdo.OrganizationSDO::getCode).orElse(ORG_SALES_ORGANIZATION_CODE));
                placeInfoRequest.setChannelCode(CHANNELCODE);
                if (StringUtil.isNotEmpty(factoryCode)) {
                    placeInfoRequest.setFactoryCode(factoryCode);
                }
                dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);
                dimensionPropertyInfoRequestList.add(dimensionPropertyInfoRequest);
            }
        }
        log.info("AllocateApplyOrderGoodsServiceImpl_queryGoodsListNew,request:{}", JSONObject.toJSONString(dimensionPropertyInfoRequestList));
        List<ItemPriceResponse> resultList = new ArrayList<>();
        int size = dimensionPropertyInfoRequestList.size();
        List<Future<PriceQueryResponse>> futures = new ArrayList<>();
        for (int i=0;i<size;i++){
            int end = i + 50;
            int start = i;
            try{
                CompletableFuture<PriceQueryResponse> future = CompletableFuture.supplyAsync(()->{
                    PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
                    priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList.subList(start, end > size ? size : end));
                    Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPrice(priceQueryRequest);
                    if(Objects.nonNull(priceQueryResponseResult) && Objects.nonNull(priceQueryResponseResult.getResult())) {
                        PriceQueryResponse priceQueryResponse = priceQueryResponseResult.getResult();
                        return priceQueryResponse;
                    }
                    return null;
                },allocateApplyTaskExecutor);
                futures.add(future);

            }catch (Exception e){
                e.printStackTrace();
            }
            i = end - 1;
        }

        if (CollectionUtils.isNotEmpty(futures)){
            try {
                for (Future<PriceQueryResponse> future : futures) {
                    PriceQueryResponse priceQueryResponse = future.get();
                    if ( priceQueryResponse != null){
                        List<ItemPriceResponse> priceResponseList = priceQueryResponse.getItemPriceResponseList();
                        if (CollectionUtils.isNotEmpty(priceResponseList)){
                            resultList.addAll(priceResponseList);
                        }
                    }
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }

        log.info("AllocateApplyOrderGoodsServiceImpl_queryGoodsListNew,result:{}", JSONObject.toJSONString(resultList));
        if (Objects.nonNull(resultList)) {
            //到岸价map
            Map<String, BigDecimal> CIFPriceMap = new HashMap<>();
            for (ItemPriceResponse itemPriceResponse : resultList) {
                //根据货品id 获取价格
                //货品id
                String itemId = itemPriceResponse.getItemId();
                //价格 分为单位
                Long moneyAmout = itemPriceResponse.getMoneyAmout();
                if (Objects.nonNull(moneyAmout)) {
                    if (moneyAmout > 0) {
                        BigDecimal doubleValue = new BigDecimal(moneyAmout.doubleValue() / 100).setScale(2, RoundingMode.HALF_UP);
                        CIFPriceMap.put(itemId, doubleValue);
                    }
                }
            }
            for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                    BigDecimal cIFPrice = CIFPriceMap.get(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                    if (Objects.nonNull(cIFPrice)) {
                        allocateApplyOrderQueryGoodsListDateilResponse.setCIFPrice(cIFPrice);
                        allocateApplyOrderQueryGoodsListDateilResponse.setPrice(cIFPrice);
                    }
                }
            }
        }
        return Result.success(scItemGoodsList);
    }

    //设置货品倍数
    private void setUpScItemMultiple(List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList){
        if (CollectionUtils.isEmpty(scItemGoodsList)){
            return;
        }
        List<String> scItemIds = scItemGoodsList.stream().map(AllocateApplyOrderQueryGoodsListResponse::getGoodsList)
                .filter(CollectionUtils::isNotEmpty)
                .flatMap(Collection::stream)
                .map(AllocateApplyOrderQueryGoodsListDateilResponse::getId)
                .filter(StringUtils::isNotBlank)
                .distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(scItemIds)){
            return;
        }
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.setScItemIdList(scItemIds);
        queryRequest.setLimit(scItemIds.size() > MAX_PAGE_SIZE ? MAX_PAGE_SIZE : scItemIds.size());
        log.info("AllocateApplyOrderGoodsServiceImpl_multiple_query_request:{}", JSON.toJSONString(scItemIds) + scItemIds.size());
        Result<List<ScItemMultiple>> query = scItemMultipleReadService.query(queryRequest);
        log.info("AllocateApplyOrderGoodsServiceImpl_multiple_query_result:{}",JSON.toJSONString(query));
        if (query == null || CollectionUtils.isEmpty(query.getResult())){
            return;
        }
        Map<String, ScItemMultiple> scItemMultipleMap = query.getResult().stream()
                .collect(Collectors.toMap(ScItemMultiple::getScItemId, x -> x, (a, b) -> a));
        scItemGoodsList.forEach(response -> {
            if (CollectionUtils.isNotEmpty(response.getGoodsList())){
                response.getGoodsList().forEach(goods -> {
                    if (goods != null && scItemMultipleMap.containsKey(goods.getId())){
                        ScItemMultiple scItemMultiple = scItemMultipleMap.get(goods.getId());
                        if (scItemMultiple != null && scItemMultiple.getMultiple() != null){
                            goods.setScItemMultiple(scItemMultiple.getMultiple());
                        }
                    }
                });
            }
        });
    }
}
